package org.jeecg.modules.lab.device.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.cronJob.MyEnum;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.jeecg.modules.lab.device.entity.LabDevice;
import org.jeecg.modules.lab.device.service.ILabDeviceService;
import org.jeecg.modules.lab.device.vo.LabDevRunPage;
import org.jeecg.modules.lab.device.vo.LabDevicePage;
import org.jeecg.modules.lab.device.vo.DevResult;
import org.jeecg.modules.lab.documents.entity.LabDocuments;
import org.jeecg.modules.lab.documents.management_technology.lab_technology.controller.LabTechnologyController;
import org.jeecg.modules.lab.documents.management_technology.lab_technology.entity.LabTechnology;
import org.jeecg.modules.lab.documents.management_technology.lab_technology.service.impl.LabTechnologyServiceImpl;
import org.jeecg.modules.lab.documents.service.ILabDocumentsService;
import org.jeecg.modules.lab.utensil.entity.LabUtensil;
import org.jeecg.modules.lab.utensil.service.ILabUtensilService;
import org.jeecg.modules.lab.utensil.vo.UteResult;
import org.jeecg.modules.lab.util.ImportExportUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Month;
import java.time.Year;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 实验室设备信息
 * @Author: jeecg-boot
 * @Date: 2023-07-05
 * @Version: V1.0
 */
@Api(tags = "实验室设备信息", value = "实验")
@RestController
@RequestMapping("/device/labDevice")
@Slf4j
public class LabDeviceController extends JeecgController<LabDevice, ILabDeviceService> {
    @Autowired
    private ILabDeviceService labDeviceService;

    @Autowired
    private ILabUtensilService labUtensilService;

    @Autowired
    private ILabCronJobService labCronJobService;

    @Autowired
    private ILabDocumentsService labDocumentsService;

    /**
     * 分页列表查询
     *
     * @param labDevice
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "实验室设备信息-分页列表查询")
    @ApiOperation(value = "实验室设备信息-分页列表查询", notes = "实验室设备信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<LabDevice>> queryPageList(LabDevice labDevice,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                  HttpServletRequest req) {
        QueryWrapper<LabDevice> queryWrapper = QueryGenerator.initQueryWrapper(labDevice, req.getParameterMap());
        Page<LabDevice> page = new Page<LabDevice>(pageNo, pageSize);
        IPage<LabDevice> pageList = labDeviceService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    //查询待维修设备
    @GetMapping(value = "/upkeep")
    public Result<IPage<LabDevice>> upkeepList(LabDevice labDevice,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                               HttpServletRequest req) {
        QueryWrapper<LabDevice> queryWrapper = QueryGenerator.initQueryWrapper(labDevice, req.getParameterMap());
        Page<LabDevice> page = new Page<LabDevice>(pageNo, pageSize);
        queryWrapper.eq("status", "待维修");
        IPage<LabDevice> pageList = labDeviceService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    //扫设备码获取设备使用状态
    @GetMapping(value = "/getStatus")
    public Result<DevResult> getStatus(@RequestParam String deviceId) {
        LabDevice labDevice = labDeviceService.getById(deviceId);
        DevResult devResult = new DevResult();
        if (labDevice != null) {
            if ("闲置".equals(labDevice.getUseStatus())) {
                if ("在用".equals(labDevice.getStatus()) || "降级使用".equals(labDevice.getStatus())) {
                    devResult.setCode("0");
                    devResult.setLabDevice(labDevice);
                    return Result.ok(devResult);
                } else {
                    devResult.setCode("1");
                    devResult.setMessage("设备" + labDevice.getStatus() + "，请更换设备！");
                    return Result.ok(devResult);
                }
            } else if ("使用中".equals(labDevice.getUseStatus())) {
                devResult.setCode("1");
                devResult.setMessage("设备使用中，请更换设备！");
                return Result.ok(devResult);
            } else {
                devResult.setCode("0");
                devResult.setLabDevice(labDevice);
                return Result.ok(devResult);
            }
        } else {
            return Result.error("设备不存在!!!");
        }
    }


    /**
     * 自定义sql查询设备和器具
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@AutoLog(value = "实验室设备信息-自定义sql查询设备和器具")
    @ApiOperation(value = "实验室设备信息-自定义sql查询设备和器具", notes = "实验室设备信息-自定义sql查询设备和器具")
    @GetMapping(value = "/queryDevAndUteList")
    public Result<IPage<LabDevicePage>> queryDevAndUteList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "50") Integer pageSize,
                                                           @RequestParam(name = "devName", defaultValue = "") String devName,
                                                           @RequestParam(name = "devNum", defaultValue = "") String devNum,
                                                           @RequestParam(name = "status", defaultValue = "") String status,
                                                           @RequestParam(name = "devType", defaultValue = "") String devType) {
        List<LabDevicePage> labDevicelist = labDeviceService.queryDeviceAndUtensil(devName, devNum, status, devType);
        List<LabDevicePage> labDevicePages = labDevicelist.stream().skip((pageNo - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        Page<LabDevicePage> page = new Page<LabDevicePage>(pageNo, pageSize);
        page.setTotal(labDevicelist.size());
        page.setRecords(labDevicePages);
        return Result.OK(page);
    }


    /**
     * 设备运行记录统计
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "实验室设备信息-设备运行记录统计", notes = "实验室设备信息-设备运行记录统计")
    @GetMapping(value = "/sumDevRunTime")
    public Result<IPage<LabDevRunPage>> sumDevRunTime(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "50") Integer pageSize,
                                                      @RequestParam(name = "devId", defaultValue = "") String devId,
                                                      @RequestParam(name = "devName", defaultValue = "") String devName,
                                                      @RequestParam(name = "devNum", defaultValue = "") String devNum,
                                                      @RequestParam(name = "devModel", defaultValue = "") String devModel,
                                                      @RequestParam(name = "status", defaultValue = "") String status,
                                                      @RequestParam(name = "startTime", defaultValue = "") String startTime,
                                                      @RequestParam(name = "endTime", defaultValue = "") String endTime) {
        List<LabDevRunPage> labDevicelist = labDeviceService.getSumDevRunTime(devId, devName, devNum, devModel, status, startTime, endTime);
        List<LabDevRunPage> labDevicePages = labDevicelist.stream().skip((pageNo - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        Page<LabDevRunPage> page = new Page<LabDevRunPage>(pageNo, pageSize);
        page.setTotal(labDevicelist.size());
        page.setRecords(labDevicePages);
        return Result.OK(page);
    }

    /**
     * 添加
     *
     * @param labDevice
     * @return
     */
    @AutoLog(value = "实验室设备信息-添加")
    @ApiOperation(value = "实验室设备信息-添加", notes = "实验室设备信息-添加")
//	@RequiresPermissions("device:lab_device:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody LabDevice labDevice) {
        labDeviceService.saveAll(labDevice);

        String rulesDoc = labDevice.getRulesDoc();
        if (!"".equals(rulesDoc)) {
            LabDocuments labDocuments = new LabDocuments();
            labDocuments.setManagements("技术类");
            labDocuments.setDocType("设备");
            labDocuments.setDisplayName(labDevice.getDevName());
            labDocuments.setCountdocId(labDevice.getId());
            labDocuments.setUploadFiles(rulesDoc);
            labDocuments.setSynFlag("0");
            labDocumentsService.save(labDocuments);
        }

        if (MyEnum.sync) {
            long time = new Date().getTime();
            List<LabCronJob> jobs = new ArrayList<>();
            jobs.add(new LabCronJob("lab_device", "0", time, 1));
            jobs.add(new LabCronJob("lab_utensil", "0", time, 2));
            jobs.add(new LabCronJob("lab_documents", "0", time, 3));
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param labDevice
     * @return
     */
    @AutoLog(value = "实验室设备信息-编辑")
    @ApiOperation(value = "实验室设备信息-编辑", notes = "实验室设备信息-编辑")
//	@RequiresPermissions("device:lab_device:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody LabDevice labDevice) {


        List<LabCronJob> jobs = new ArrayList<>();
        long time = new Date().getTime();

        labDevice.setSynFlag("1");
        LabUtensil utensil = labUtensilService.getOne(new LambdaQueryWrapper<LabUtensil>().eq(LabUtensil::getDeviceId, labDevice.getId()));
        if (utensil != null) {
            labDeviceService.updateAll(labDevice, utensil);
            jobs.add(new LabCronJob("lab_device", "1", time, 1));
            jobs.add(new LabCronJob("lab_utensil", "1", time, 2));
        } else {
            labDeviceService.updateById(labDevice);
            jobs.add(new LabCronJob("lab_device", "1", time, 1));
        }
        QueryWrapper<LabDocuments> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("countdoc_id", labDevice.getId());
        LabDocuments one = labDocumentsService.getOne(queryWrapper);
        String rulesDoc = labDevice.getRulesDoc();
        if (one == null && !"".equals(rulesDoc)) {
            LabDocuments labDocuments = new LabDocuments();
            labDocuments.setManagements("技术类");
            labDocuments.setDocType("设备");
            labDocuments.setDisplayName(labDevice.getDevName());
            labDocuments.setCountdocId(labDevice.getId());
            labDocuments.setUploadFiles(rulesDoc);
            labDocuments.setSynFlag("0");
            labDocumentsService.save(labDocuments);
            jobs.add(new LabCronJob("lab_documents", "0", time, 3));
        } else {
            one.setUploadFiles(labDevice.getRulesDoc());
            one.setDisplayName(labDevice.getDevName());
            one.setSynFlag("1");
            labDocumentsService.updateById(one);
            jobs.add(new LabCronJob("lab_documents", "1", time, 3));
        }
        if (MyEnum.sync) {
            labCronJobService.saveBatch(jobs);
        }

        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "实验室设备信息-通过id删除")
    @ApiOperation(value = "实验室设备信息-通过id删除", notes = "实验室设备信息-通过id删除")
//	@RequiresPermissions("device:lab_device:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {

        long time = new Date().getTime();
        List<LabCronJob> jobs = new ArrayList<>();

        LabDevice labDevice = labDeviceService.getById(id);
        labDeviceService.removeById(id);
        String condition1 = "id='" + id + "'";
        jobs.add(new LabCronJob("lab_device", "2", condition1, time, 1));
        // todo 删除器具
        if (labDevice.getCheckMark().equals("1")) {
            labUtensilService.removeByDeviceId(id);
            String condition2 = "device_id='" + id + "'";
            jobs.add(new LabCronJob("lab_utensil", "2", condition2, time, 2));
        }
        // todo 删除文档
        QueryWrapper<LabDocuments> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("countdoc_id", id);
        LabDocuments one = labDocumentsService.getOne(queryWrapper);
        if (one != null) {
            labDocumentsService.removeById(one);
            String condition2 = "countdoc_id='" + one.getId() + "'";
            jobs.add(new LabCronJob("lab_documents", "2", condition2, time, 3));
        }

        if (MyEnum.sync) {
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "实验室设备信息-批量删除")
    @ApiOperation(value = "实验室设备信息-批量删除", notes = "实验室设备信息-批量删除")
//	@RequiresPermissions("device:lab_device:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        String[] idList = ids.split(",");
        labDeviceService.removeByIds(Arrays.asList(ids.split(",")));

        List<String> listIdA = new ArrayList<>();
        List<String> listIdB = new ArrayList<>();
        QueryWrapper<LabUtensil> queryWrapperA = new QueryWrapper<>();
        QueryWrapper<LabDocuments> queryWrapperB = new QueryWrapper<>();
        for (int i = 0; i < idList.length; i++) {
            String devId = idList[i];
            //todo 删除器具
            queryWrapperA.eq("device_id", devId);
            LabUtensil utensil = labUtensilService.getOne(queryWrapperA);
            if (utensil != null) {
                listIdA.add(utensil.getId());
                labUtensilService.removeById(utensil);
            }
            //todo 删除文档
            queryWrapperB.eq("countdoc_id", devId);
            LabDocuments labDocuments = labDocumentsService.getOne(queryWrapperB);
            if (labDocuments != null) {
                listIdB.add(labDocuments.getId());
                labDocumentsService.removeById(labDocuments);
            }
        }

        if (MyEnum.sync) {
            long time = new Date().getTime();
            labCronJobService.saveCronBatch("lab_device", "2", time, idList);
            String[] uIds = listIdA.toArray(new String[0]);
            labCronJobService.saveCronBatch("lab_utensil", "2", time, uIds);
            String[] dIds = listIdB.toArray(new String[0]);
            labCronJobService.saveCronBatch("lab_documents", "2", time, dIds);
        }
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "实验室设备信息-通过id查询")
    @ApiOperation(value = "实验室设备信息-通过id查询", notes = "实验室设备信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<LabDevice> queryById(@RequestParam(name = "id", required = true) String id) {
        LabDevice labDevice = labDeviceService.getById(id);
        if (labDevice == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(labDevice);
    }


    /**
     * 导出excel
     *
     * @param request
     * @param labDevice
     */
//    @RequiresPermissions("device:lab_device:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LabDevice labDevice) {
        return super.exportXls(request, labDevice, LabDevice.class, "实验室设备信息");
    }

    /**
     * 导出excel设备和器具
     */
    @RequestMapping(value = "/exportXlsDevAndUte")
    public ModelAndView exportXlsDevAndUte(@RequestParam(name = "devName", defaultValue = "") String devName,
                                           @RequestParam(name = "devNum", defaultValue = "") String devNum,
                                           @RequestParam(name = "status", defaultValue = "") String status,
                                           @RequestParam(name = "devType", defaultValue = "") String devType) {

        List<LabDevicePage> labDevicePages = labDeviceService.queryDeviceAndUtensil(devName, devNum, status, devType);
        ImportExportUtil exportUtil = new ImportExportUtil();
        return exportUtil.exportXlsBySql(labDevicePages, LabDevicePage.class, "设备器具清单");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
//    @RequiresPermissions("device:lab_device:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LabDevice.class);
    }

}
